<template>
  <div>
    <r-search
      ref="search"
      :searchData="searchData"
      :searchForm="searchForm"
      :searchHandle="searchHandle"
    />
    <div class="retruss">
      Current Storage Rules：Whether Enable：<span style="color: #3596ff">{{
        renewalData.enable == 1 ? "Enable" : "No Enable"
      }}</span>
      ；Whether To Share Frequency And Days With The Agent：<span
        style="color: #3596ff"
        >{{ renewalData.share == 1 ? "Yes" : "No" }}</span
      >；Maximum Monthly Deposit：
      <span style="color: #3596ff">{{ renewalData.holdDay || "0" }}/day；</span
      >Or At Most：<span style="color: #3596ff"
        >{{ renewalData.total || "0" }}Number</span
      >
    </div>
    <r-table
      :isSelection="false"
      :isHandle="true"
      :isPagination="true"
      :tableData="tableData"
      :tableCols="tableCols"
      :tablePage="pagination"
      :loading="tableLoading"
      :tableHandles="tableHandles"
      @refresh="page()"
    />
    <!-- 分配暂存劵至Agent -->
    <el-dialog
      width="600px"
      title="Allocation Staging Coupon Agents"
      :visible.sync="renewalShow"
    >
      <!-- <el-form style="display: flex;justify-content: center;">
                <el-form-item label="暂存劵编号" :label-width="formLabelWidth">
                    <el-input type="text" v-model="renewalId" :disabled="true" style="width:250px" />
                </el-form-item>
            </el-form> -->
      <el-form style=" display: flex;justify-content: center;">
        <el-form-item label="Agent" :label-width="formLabelWidth">
          <el-select
            placeholder="Please Select Agent"
            :clearable="true"
            v-model="agentValue"
            style="width:250px"
            multiple
          >
            <el-option
              v-for="item in agentArr"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              :disabled="item.disabled"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div>Staging Coupon Already Allocation Agent：</div>
      <el-table :data="inquireAgentData">
        <el-table-column type="index" width="50" />
        <el-table-column property="agentId" label="Agentid" align="center" />
        <el-table-column
          property="agentName"
          label="Agent Name"
          width="150"
          align="center"
        />
        <el-table-column label="Operations" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >Delete</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="renewalShow = false">Cancel</el-button>
        <el-button type="primary" @click="affirmAgentFn">Confirm</el-button>
      </div>
    </el-dialog>
    <!-- Edit -->
    <el-dialog :title="isRedact" :visible.sync="particularsShow" width="700px">
      <el-form
        :model="renewalData"
        :status-icon="true"
        :rules="renewalRules"
        ref="renewalData"
        label-width="270px"
        class="renewalData"
      >
        <el-form-item label="Maximum Per Month Days Of Storage" prop="holdDay">
          <el-input
            type="input"
            v-model="renewalData.holdDay"
            placeholder="If the input is 0, it defaults to unlimited"
          >
            <el-button slot="append" @click="holdDayBtnFn"
              >Unlimited Days</el-button
            >
          </el-input>
        </el-form-item>
        <el-form-item label="Maximum Monthly Deposit Frequency" prop="total">
          <el-input
            type="input"
            v-model="renewalData.total"
            placeholder="If the input is 0, it defaults to Unlimited"
          >
            <el-button slot="append" @click="totalBtnFn">Unlimited</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="Whether To Enable Storage" prop="enable">
          <el-switch v-model="renewalData.enable"></el-switch>
        </el-form-item>
        <el-form-item
          label="Whether To Share Frequency And Days With The Agent"
          prop="share"
        >
          <el-switch v-model="renewalData.share"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="particularsShow = false">Cancel</el-button>
        <el-button type="primary" @click="renewalSubmit('renewalData')"
          >Confirm</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var checkToFixedTwo = (rule, value, callback) => {
      const reg = /[^\d]/g;
      if (!reg.test(value)) {
        callback();
      } else {
        return callback(new Error("Please InputInteger Number"));
      }
    };
    return {
      isRedact: "Edit",
      particularsShow: false,
      // Edit、、Add start
      renewalShow: false,
      renewalData: {
        share: false, //是否Agent共享Frequency和天数  1 是true   2 否false
        enable: false, //是否Enable 1Enabletrue   2Forbiddenfalse
        holdDay: "", //暂存天数
        total: "" //每月可领Frequency 0为Unlimited
      },
      renewalRules: {
        holdDay: [{ required: true, message: "Please Enter", trigger: "blur" }],
        total: [{ required: true, message: "Please Enter", trigger: "blur" }]
      },
      // Edit、、Add end
      tableLoading: false,
      searchData: {
        operatorId: "",
        agentId: "",
        userType: "",
        phone: ""
      },
      searchForm: [
        // { type: "input", placeholder: "Operatorid", prop: "operatorId", width: 180, },
        // { type: "input", placeholder: "Agentid", prop: "agentId", width: 180, },
        { type: "input", placeholder: "Phone", prop: "phone", width: 180 },
        {
          type: "select",
          placeholder: "User Type",
          prop: "userType",
          width: 220,
          options: [
            { label: "WeChat", value: 1 },
            { label: "Alipay", value: 2 }
          ]
        }
      ],
      searchHandle: [
        {
          label: "Search",
          type: "primary",
          plain: true,
          handle: e => {
            this.zeroFn();
            this.getData();
          }
        },
        {
          label: "Reset",
          buttonss: true,
          icon: "el-icon-refresh-right",
          handle: e => {
            this.searchData = {
              operatorId: "",
              agentId: "",
              userType: "",
              phone: ""
            };
            this.zeroFn();
            this.getData();
          }
        }
      ],
      tableHandles: [
        {
          label: "Setup Staging Rule",
          type: "primary",
          plain: true,
          handle: async e => {
            this.particularsShow = true;
            this.isRedact = "Add";
            this.possfgfeedcFn();
          }
        },
        {
          label: "Rule Allocation Agent",
          type: "primary",
          size: "mini",
          plain: true,
          handle: async row => {
            this.agentArr.forEach((o, num) => {
              o.disabled = false;
            });
            let res = await this.apis.holdAgentList();
            this.inquireAgentData = res.data || [];
            if (this.inquireAgentData.length !== 0) {
              this.inquireAgentData.forEach(i => {
                this.agentArr.forEach((o, num) => {
                  if (i.agentId === o.id) {
                    o.disabled = true;
                  }
                });
              });
              // console.log(111, this.agentArr);
            } else {
              console.log(222, this.agentArr);
            }
            this.renewalShow = true;
          }
        }
      ],
      tableData: [],
      tableCols: [
        { label: "User Name", prop: "userName" },
        {
          label: " User Type",
          prop: "userType",
          formatter: e =>
            e.userType === 1 ? "WeChat " : e.userType === 2 ? "Alipay" : "--"
        },
        { label: "Phone", prop: "phone" },
        { label: "Package Name", prop: "mealName" },
        {
          label: "Days Of Storage",
          prop: "holdDay",
          formatter: e => (e.holdDay ? e.holdDay + "/day" : "--")
        },
        // { label: "Employ情况", prop: "type", formatter: e => e.type === 1 ? 'User直接暂存 ' : e.type === 2 ? 'EmployCoupon' : '--' },
        { label: "Creation Time", prop: "ctime" }
        // {
        //     label: "Operations",
        //     type: "button",
        //     width: 300,
        //     btnList: [
        //         {
        //             label: "Edit",
        //             type: "success",
        //             size: "mini",
        //             plain: true,
        //             handle: async (row) => {
        //                 this.particularsShow = true
        //                 this.isRedact = 'Edit'
        //                 this.renewalData.id = row.id
        //                 this.renewalData.operatorId = row.operatorId
        //                 this.renewalData.validDay = row.validDay
        //                 this.renewalData.holdDay = row.holdDay
        //                 this.renewalData.total = row.total
        //                 this.renewalData.enable = row.enable == 1 ? true : false
        //             }
        //         },

        //     ]
        // },
      ],
      pagination: { limit: 10, offset: 1, total: 0 },

      agentArr: [],
      isCharge: false,
      isTemporary: false,
      dialogFormVisible: false,
      formLabelWidth: "120px",
      agentValue: [],
      inquireAgentData: []
    };
  },
  async mounted() {
    this.getData();
    this.agentFn();
    this.possfgfeedcFn();
  },
  methods: {
    zeroFn() {
      this.pagination.limit = 10;
      this.pagination.offset = 1;
      this.pagination.total = 0;
    },
    async possfgfeedcFn() {
      let res = await this.apis.holdCouponSave();
      let data = res.data || {};
      this.renewalData.enable = data.enable === 1 ? true : false;
      this.renewalData.share = data.share === 1 ? true : false;
      this.renewalData.holdDay =
        data.holdDay == 0 ? "不限天" : Number(data.holdDay);
      this.renewalData.total =
        data.total == 0 ? "Unlimited" : Number(data.total);
    },
    async handleDelete(index, row) {
      let res = await this.apis.holdHoldAgentDel(row.agentId);
      this.$message({
        type: res.code == 200 ? "success" : "error",
        message: res.msg
      });
      this.renewalShow = false;
    },

    totalBtnFn() {
      this.renewalData.total = "Unlimited";
    },
    holdDayBtnFn() {
      this.renewalData.holdDay = "不限天";
    },
    // 拿到Agentid列表
    async agentFn() {
      let res = await this.apis.agent_list({
        pageNum: this.pagination.offset,
        pageSize: this.pagination.limit
      });
      let options = [];
      res.rows.forEach(i => {
        let testAgentArr = {
          id: i.id,
          name: i.name
        };
        options.push({
          value: i.id,
          label: i.name
        });
        this.agentArr.push(testAgentArr);
      });
      // this.searchForm[this.labIndex2(this.searchForm, 'agentId')].options = options
    },
    // 分配暂存劵至Agent的确认按钮
    async affirmAgentFn() {
      if (this.agentValue.length === 0) {
        this.$message({
          message: "Please SelectAgent",
          type: "error"
        });
        return false;
      }
      let arr = [];
      this.inquireAgentData.forEach(i => {
        arr.push(i.agentId);
      });
      this.agentValue = [...arr, ...this.agentValue];
      let params = {
        agentIds: this.agentValue
      };
      let res = await this.apis.holdCouponAllotAgent(params);
      this.agentValue = [];
      this.$message({
        type: res.code == 200 ? "success" : "error",
        message: res.msg
      });
      this.renewalShow = false;
    },
    // Edit---Add确认按钮
    async renewalSubmit(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          this.renewalData.share = this.renewalData.share ? 1 : 2;
          this.renewalData.enable = this.renewalData.enable ? 1 : 2;

          this.renewalData.holdDay =
            this.renewalData.holdDay == "不限天"
              ? 0
              : Number(this.renewalData.holdDay);
          this.renewalData.total =
            this.renewalData.total == "Unlimited"
              ? 0
              : Number(this.renewalData.total);
          let res = await this.apis.holdCouponEdit(this.renewalData);
          this.$message({
            message: res.msg,
            type: res.code == 200 ? "success" : "error"
          });
          this.particularsShow = false;
          this.getData();
        } else {
          return false;
        }
      });
    },
    // 列表
    async getData() {
      let parm = {
        ...this.searchData,
        ...{
          pageNum: this.pagination.offset,
          pageSize: this.pagination.limit
        }
      };
      let res = await this.apis.holdGetUserHoldRecord(parm);
      this.tableData = res.rows || [];
      this.pagination.total = res.total;
    },
    // 分页
    page() {
      this.getData();
    }
  }
};
</script>

<style scoped lang="scss">
.agentIdClass {
  margin-bottom: 20px;
}

.agentIdClass > .el-select {
  margin-left: 8%;
}

.agentIdClass1 > .el-select {
  margin-left: 11%;
}

.w54MB20 {
  width: 76%;
  margin-bottom: 10px;
}

.fJ {
  float: auto;
}

.retruss {
  color: #aaa;
  margin-bottom: 20px;
}
</style>
